package com.pw.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pw.gmall.realtime.common.Constant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author: linux_future
 * @since: 2022/3/21
 **/
public class DimUtils {
    public static void main(String[] args) throws Exception {
        Connection conn = JdbcUtils.getJdbcConnect(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL, null, null);
        List<JSONObject> list = JdbcUtils.queryList(conn, "select * from dim_user_info where id=?", new Object[]{"1808"}, JSONObject.class);
        for (JSONObject jsonObject : list) {
            System.out.println(jsonObject);
        }
    }

    public static JSONObject readDimFromPhoenix(Connection conn, String tableName, Long id) throws Exception {
        //System.out.println("=============readDimFromPhoenix===========");
        String sql = "select * from " + tableName + " where id=?";
        String[] args = {id.toString()};
        List<JSONObject> list = JdbcUtils.queryList(conn, sql, args, JSONObject.class);
        //System.out.println("readDimFromPhoenix list:"+list.toString());
        if(list.size()>0){
            return list.get(0);
        }else{
            System.out.println("tableName："+ tableName +" and id:"+id);
            return null;
        }
    }

    public static JSONObject readDim(Jedis jedis, Connection conn, String tableName, Long id) throws Exception {
        //System.out.println(" readDim==============");
        //先从redis中读取数据
        JSONObject dim = readDimFromRedis(jedis, tableName, id);

        // redis没有数据，再从hbase中获取数据，并保存数据进入redis
        if (dim == null) {
            dim = readDimFromPhoenix(conn, tableName, id);
            writeDimToRedis(jedis, tableName, id, dim);
            System.out.println("走数据库: " + tableName + "  " + id);
        } else {
            System.out.println("走缓存: " + tableName + "  " + id);
        }
        return dim;
    }

    private static void writeDimToRedis(Jedis jedis, String tableName, Long id, JSONObject dim) {
        //System.out.println("writeDimToRedis========================");
        String key = "dim_" + tableName + "_" + id;
        jedis.setex(key, 2 * 24 * 60 * 60, dim.toJSONString());
    }

    private static JSONObject readDimFromRedis(Jedis jedis, String tableName, Long id) {
        //System.out.println("readDimFromRedis========================");
        String key = "dim_" + tableName + "_" + id;
        String dim = jedis.get(key);
        if (dim != null) {
            return JSON.parseObject(dim);
        }
        System.out.println("结果："+dim);
        return null;
    }
}
